package com.digua.base.util

import android.Manifest.permission
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo
import androidx.annotation.RequiresPermission
import com.blankj.utilcode.util.NetworkUtils
import com.digua.base.base.App


/**
 * 网络工具类
 */
class NetWorkUtil {

    companion object {
        /**
         * 返回网络是否链接
         */
        @RequiresPermission(permission.ACCESS_NETWORK_STATE)
        fun isConnected() = getActiveNetworkInfo()?.isConnected ?: false

        /**
         * 返回网络是否断开
         */
        @RequiresPermission(permission.ACCESS_NETWORK_STATE)
        fun isNotConnected() = !isConnected()

        /**
         * 获取网络信息
         *
         * @return
         */
        @RequiresPermission(permission.ACCESS_NETWORK_STATE)
        private fun getActiveNetworkInfo(): NetworkInfo? {
            val cm = App.instance.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            return cm.activeNetworkInfo
        }

        /**
         * 判断是否是局域网IP(简陋版)
         *
         * @return
         */
        fun isLocalIP(ip: String): Boolean {
            if (StrUtil.hasBlank(ip) || isNotConnected()) return false
            var thisIp = NetworkUtils.getIPAddress(true)
            if (StrUtil.isBlank(thisIp)) return false
            thisIp = thisIp.substring(0, thisIp.lastIndexOf(".") + 1)
            return ip.startsWith(thisIp)
        }
    }
}